﻿using System.Text;

namespace AOP
{
    //
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    using Microsoft.AspNetCore.Mvc.ViewFeatures;
    using Common;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc.ModelBinding;

    public class AopExceptionFilterAttribute : ExceptionFilterAttribute
    {

        private readonly IHostingEnvironment _hostingEnvironment;
        private readonly IModelMetadataProvider _modelMetadataProvider;

        public AopExceptionFilterAttribute(
            IHostingEnvironment hostingEnvironment,
            IModelMetadataProvider modelMetadataProvider
            )
        {
            _hostingEnvironment = hostingEnvironment;
            _modelMetadataProvider = modelMetadataProvider;
        }

        /// <summary>
        /// 异常拦截
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            if (!_hostingEnvironment.IsDevelopment())
            {
                // do nothing
                return;
            }

            //判断是否为 ajax 请求
            var IsAjaxRequest = context.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";

            //判断是否是自定义异常类型
            if (context.Exception is MessageBox)
            {

                if (IsAjaxRequest)
                {
                    context.Result = new JsonResult(MessageBox.errorModel);
                }
                else
                {
                    var errorModel = new ErrorModel(context.Exception.Message);
                    var sb = new StringBuilder();
                    sb.Append("<script src=\"/HzyUI/lib/jquery/jquery-2.1.4.min.js\"></script>");
                    sb.Append("<script src=\"/Admin/lib/layer-v3.1.1/layer/layer.js\"></script>");
                    sb.Append("<script src=\"/Admin/js/admin.js\"></script>");
                    sb.Append("<script type='text/javascript'>");
                    sb.Append("$(function(){ admin.alert('" + errorModel.msg.Trim().Replace("'", "“").Replace("\"", "”") + "', '警告'); });");
                    sb.Append("</script>");
                    context.Result = new ContentResult() { Content = sb.ToString(), ContentType = "text/html;charset=utf-8;" };
                }
                context.HttpContext.Response.StatusCode = 200;
            }
            else
            {
                Tools.log.WriteLog(context.Exception, context.HttpContext.Connection.RemoteIpAddress.ToString());

                var errorModel = new ErrorModel(context.Exception);
                if (IsAjaxRequest)
                {
                    context.Result = new JsonResult(errorModel);
                }
                else
                {
                    var result = new ViewResult() { ViewName = AppConfig.ErrorPageUrl };
                    result.ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
                    result.ViewData.Add("Exception", errorModel);
                    context.Result = result;
                }
            }
            context.HttpContext.Response.StatusCode = 200;
            //表示异常已处理
            context.ExceptionHandled = true;
        }

        //public override Task OnExceptionAsync(ExceptionContext context)
        //{
        //    return base.OnExceptionAsync(context);
        //}


    }
}
